import { Component, OnInit } from '@angular/core';

import * as moment from 'moment';

import { ApiService } from '~/api/services';
import { maptreedata } from '~/utils/funcs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  title = 'myMoney';
  hello = '';
  isVisible = false;
  datalist = [];
  result: DialogData = { id: 0,  title: '', price: 0, time: new Date().toDateString(), category_id: 0 };
  private api: ApiService;
  nodes = [];
  constructor(apiSvr: ApiService) {
    this.api = apiSvr;
  }
  showModal(): void {
    this.isVisible = true;
  }
  editModal(item): void {
    this.result.id = item.id;
    this.result.title = item.title;
    this.result.price = item.price;
    this.result.time = item.time;
    this.result.category_id = item.category_id;
    this.isVisible = true;
  }
  handleOk(): void {
    console.log('Button ok clicked!');
    this.isVisible = false;
    const vtime = moment.parseZone(this.result.time).format('YYYY-MM-DD');
    if (this.result.id > 0){
      this.api.update({body:{
          id: this.result.id,
          title: this.result.title,
          price: this.result.price,
          time: vtime,
          category_id: this.result.category_id
      }
      }).subscribe(d => {
        if (d) {
          this.refshdata();
        }
      });
    } else {

    this.api
      .add({
        body: {
          id: 0,
          title: this.result.title,
          price: this.result.price,
          time: vtime,
          category_id: this.result.category_id
        }
      })
      .subscribe(d => {
        if (d) {
          this.refshdata();
        }
      });
    }
  }


  handleCancel(): void {
    console.log('Button cancel clicked!');
    this.isVisible = false;
  }

  ngOnInit() {
    this.title = 'hhhhhh';
    this.api.hello().subscribe(d => {
      this.hello = d.Hello;
    });
    this.api.getall().subscribe(d => {
      this.datalist = d;
    });
    this.api.getCategory().subscribe(d => {
      this.nodes = maptreedata(d);
    });
  }
  private refshdata(){
    this.api.getall().subscribe(e => {
      this.datalist = e;
      this.result = { id: 0, title: '', price: 0, time: new Date().toDateString(), category_id: 0 };
    });
  }
}

export interface DialogData {
  id: number;
  title: string;
  price: number;
  time: string;
  category_id: number;
}

